<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品编码" prop="goodsId">
        <el-input
          v-model="queryParams.goodsId"
          placeholder="请输入商品编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账单名称" prop="billName">
        <el-input
          v-model="queryParams.billName"
          placeholder="请输入账单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品串号" prop="goodsSn">
        <el-input
          v-model="queryParams.goodsSn"
          placeholder="请输入商品串号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="成本价" prop="costPrice">
        <el-input
          type="number"
          v-model="queryParams.costPrice"
          placeholder="请输入成本价"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售价" prop="sellPrice">
        <el-input
          type="number"
          v-model="queryParams.sellPrice"
          placeholder="请输入销售价"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="买家" prop="buyers">
        <el-input
          v-model="queryParams.buyers"
          placeholder="请输入买家"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="销售人" prop="sellBy">
        <el-input
          v-model="queryParams.sellBy"
          placeholder="请输入销售人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收款人" prop="payee">
        <el-select v-model="queryParams.payee" placeholder="请选择收款人" clearable size="small">
          <el-option v-for="pay in payeeOption" :label="pay.dictLabel" :value="pay.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentType">
        <el-select v-model="queryParams.paymentType" placeholder="请选择支付方式" clearable size="small">
          <el-option v-for="payment in paymentTypeOptions"
                     :label="payment.label" :value="payment.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="待审核" :value="1" />
          <el-option label="已审核" :value="2" />
          <el-option label="退货" :value="3" />
          <el-option label="作废" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option label="商品出售" :value="1" />
          <el-option label="自定义账单" :value="2" />
          <el-option label="退货账单" :value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="报价师" prop="offerName">
        <el-select v-model="queryParams.offerName" placeholder="请选择报价师" clearable size="small">
          <el-option v-for="item in offerNameOptions" :label="item.dictLabel" :value="item.dictValue" />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          size="small"
          v-model="createTimeRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :unlink-panels="true"
          @change="createTimeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="修改时间">
        <el-date-picker
          size="small"
          v-model="updateTimeRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :unlink-panels="true"
          @change="updateTimeChange"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['recovery:bill:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-s-check"
          size="mini"
          @click="handleStatus"
          :disabled="multiple"
          v-hasPermi="['recovery:bill:edit']"
        >审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-printer"
          size="mini"
          @click="gotoPrinting"
          :disabled="multiple"
        >出账单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleCondition"
          v-hasPermi="['recovery:bill:condition']"
        >支付统计</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['recovery:bill:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="3">
        <div style="display: flex;flex-direction: row" v-hasPermi="['recovery:bill:sum']">
          <div v-if="dataOpen" @click="closeData"><img style="width: 40px" src="../../../assets/images/zy.png" /></div>
          <div v-else @click="openData"><img style="width: 40px;" src="../../../assets/images/by.png" /></div>
          <div style="margin-left: 10px;display: flex;flex-direction: row" v-if="dataOpen">
            <el-tag type="info" style="margin-right: 10px">成本额: {{dataPrice.costPrice}}</el-tag>
            <el-tag style="margin-right: 10px">销售额: {{dataPrice.sellPrice}}</el-tag>
            <el-tag type="success">利润额: {{dataPrice.profitPrice}}</el-tag>
          </div>
        </div>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="billList" @selection-change="handleSelectionChange" :row-class-name="setRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="账单编号" align="center" prop="billId" />
      <el-table-column label="商品信息" align="center" prop="billName" width="180">
        <template v-slot="scope">
          <el-tooltip effect="light" placement="top">
            <div slot="content">
              <div>编码: {{scope.row.goodsId}}</div>
              <div>名称: {{scope.row.billName}}</div>
              <div>IMEI: {{scope.row.goodsSn}}</div>
              <div>配件: {{scope.row.partsInfo}}</div>
            </div>
            <div style="text-align: left;cursor: pointer" @click="handleDetail(scope.row)" class="link-type">
              <div class="table-row" v-if="scope.row.goodsId">编码: {{scope.row.goodsId}}</div>
              <div class="table-row" v-if="scope.row.billName">名称: {{scope.row.billName}}</div>
              <div class="table-row" v-if="scope.row.goodsSn">IMEI: {{scope.row.goodsSn}}</div>
              <div class="table-row" v-if="scope.row.partsInfo">配件: {{scope.row.partsInfo}}</div>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="销售价" align="center" prop="sellPrice" />
      <el-table-column label="利润" align="center" prop="profit" />
      <el-table-column label="买家" align="center" prop="buyers" :show-overflow-tooltip="true" />
      <el-table-column label="收款账户" align="center" prop="payee" :formatter="payeeFormatter" />
      <el-table-column label="账单类型" align="center" prop="type" :formatter="typeFormatter" />
      <el-table-column label="支付方式" align="center" prop="paymentType" width="100">
        <template slot-scope="scope">
          <el-tag
            v-for="payment in paymentTypeOptions"
            v-if="payment.value === scope.row.paymentType"
            :type="payment.type"
          >
            {{payment.label}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支付详情" align="center" prop="paymentDetail" width="120">
        <template slot-scope="scope">
          <div v-if="Number(scope.row.paymentType) === 4">
            <div v-for="json in JSON.parse(scope.row.paymentDetail)" style="display: flex;flex-direction: row;margin-bottom: 5px">
              <el-tag v-for="payment in paymentTypeOptions"
                      v-if="payment.value === parseInt(json.type)"
                      :type="payment.type"
              >{{payment.label + " " + json.price + " " + payeeFormatter(json)}}</el-tag>
            </div>
          </div>
          <div v-else-if="Number(scope.row.paymentType) === 6">
            <span style="size: 14px">单号: {{bankNumber(scope.row)}}</span>
          </div>
          <div v-else>
            <span>{{scope.row.paymentDetail}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 1">待审核</el-tag>
          <el-tag type="success" v-else-if="scope.row.status === 2">已审核</el-tag>
          <el-tag type="warning" v-else-if="scope.row.status === 3">退货</el-tag>
          <el-tag type="danger" v-else>作废</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="销售人" align="center" prop="sellBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="90">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报价师" align="center" prop="offerName" :formatter="offerNameFormat" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" width="100" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status === 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['recovery:bill:edit']"
          >修改</el-button>
          <el-button v-if="scope.row.status === 1"
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="handleUpdateByStatus(scope.row, 2)"
            v-hasPermi="['recovery:bill:edit']"
          >审核</el-button>
          <el-button v-if="scope.row.type === 1 && scope.row.status !== 3"
            size="mini"
            type="text"
            icon="el-icon-takeaway-box"
            @click="handleReturnGoods(scope.row)"
            v-hasPermi="['recovery:bill:out']"
          >退货</el-button>
          <el-button v-if="scope.row.type !== 1 && scope.row.status !== 4"
            size="mini"
            type="text"
            icon="el-icon-s-release"
            @click="handleUpdateByStatus(scope.row, 4)"
            v-hasPermi="['recovery:bill:edit']"
          >作废</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="商品退货" :visible.sync="outGoodsOpen" width="500px" append-to-body>
      <el-form ref="outGoodsForm" v-model="outGoodsForm" label-width="80px">
        <el-form-item label="商品编码: " prop="goodsId">
          {{outGoodsForm.goodsId}}
        </el-form-item>
        <el-form-item label="商品名称: " prop="billName">
          {{outGoodsForm.billName}}
        </el-form-item>
        <el-form-item label="销售价: " prop="sellPrice">
          {{outGoodsForm.sellPrice}}
        </el-form-item>
        <el-form-item label="退回金额" prop="costPrice">
          <el-input-number v-model="outGoodsForm.costPrice" :min="0" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="outGoodsForm.remark" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="outSubmitForm">确 定</el-button>
        <el-button @click="outCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--goodsDetail-->
    <el-dialog title="商品详情" :visible.sync="detailOpen" width="60%" append-to-body>
      <el-form v-if="detailInfo != null" label-width="80px">
        <el-row>
          <el-col :span="12" v-if="detailInfo.goodsInfo != null">
            <el-form-item label="商品编码: " style="margin: 2px">{{detailInfo.goodsInfo.goodsId}}</el-form-item>
            <el-form-item label="商品名称: " style="margin: 2px">{{detailInfo.goodsInfo.goodsName}}</el-form-item>
          </el-col>
          <el-col :span="12" v-if="detailInfo.goodsInfo != null">
            <el-form-item label="串号: " style="margin: 2px">{{detailInfo.goodsInfo.goodsSn}}</el-form-item>
            <el-form-item label="规格: " style="margin: 2px">{{detailInfo.goodsInfo.printing}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <div v-if="detailInfo.goodsInfo != null">
              <el-form-item label="验机人: " style="margin: 2px">{{userFormatter(detailInfo.goodsInfo.testUserId)}}</el-form-item>
              <el-form-item label="验机时间: " style="margin: 2px">{{detailInfo.goodsInfo.testTime}}</el-form-item>
            </div>
            <el-form-item label="成本价: " style="margin: 2px">{{detailInfo.row.costPrice}}</el-form-item>
            <el-form-item label="类型: " style="margin: 2px">{{typeFormatter(detailInfo.row)}}</el-form-item>
            <el-form-item label="修改人: " style="margin: 2px">{{detailInfo.row.updateBy}}</el-form-item>
            <el-form-item label="配送类型: " style="margin: 2px">{{giveFormat(detailInfo.row)}}</el-form-item>
            <el-form-item label="配送单号: " style="margin: 2px">{{detailInfo.row.giveNumber}}</el-form-item>
            <el-form-item label="配送费: " style="margin: 2px">{{detailInfo.row.givePrice}}</el-form-item>
          </el-col>
          <el-col :span="12">
            <div v-if="detailInfo.goodsInfo != null">
              <el-form-item label="仓库: " style="margin: 2px">{{stockFormatter(detailInfo.goodsInfo.stockId)}}</el-form-item>
              <el-form-item label="仓位: " style="margin: 2px">{{detailInfo.goodsInfo.stockNum}}</el-form-item>
            </div>
            <el-form-item label="创建人: " style="margin: 2px">{{detailInfo.row.createBy}}</el-form-item>
            <el-form-item label="报价师: " style="margin: 2px" v-if="detailInfo.collectInfo != null">{{offerNameFormat(detailInfo.collectInfo)}}</el-form-item>
            <el-form-item label="修改时间: " style="margin: 2px">{{detailInfo.row.updateTime}}</el-form-item>
            <el-form-item label="配件: " style="margin: 2px">{{detailInfo.row.partsInfo}}</el-form-item>
            <el-form-item label="配件成本: " style="margin: 2px">{{detailInfo.row.partsPrice}}</el-form-item>
          </el-col>

          <el-col :span="24" v-if="detailInfo.goodsInfo != null">
            <el-form-item label="验机报告: " style="margin: 2px">{{testValuesFormatter(detailInfo.goodsInfo.testValues)}}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>

    <!-- conditionForm -->
    <el-dialog title="支付数据统计" :visible.sync="conditionOpen" width="500px" append-to-body>
      <el-form ref="conditionParams" :model="conditionParams" label-width="80px">
        <el-form-item label="时间单位" prop="timeType">
          <el-radio-group v-model="conditionParams.timeType" size="mini" @change="conditionChange">
            <el-radio label="day" border>日</el-radio>
            <el-radio label="week" border>周</el-radio>
            <el-radio label="month" border>月</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账户统计" prop="hasPayee">
          <el-radio-group v-model="conditionParams.hasPayee" size="mini" @change="conditionChange">
            <el-radio label="no" border>否</el-radio>
            <el-radio label="yes" border>是</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-for="item in conditionData" :label="item.payee == null ? '结果':payeeFormatter({payee: item.payee})">
          <el-tag v-show="item.zhb != null">支付宝: {{item.zhb}}</el-tag>
          <el-tag type="success" v-show="item.wx != null" style="margin-left: 2px">微信: {{item.wx}}</el-tag>
          <el-tag type="warning" v-show="item.xj != null" style="margin-left: 2px">现金: {{item.xj}}</el-tag>
          <el-tag type="danger" v-show="item.dk != null" style="margin-left: 2px">旧机抵扣: {{item.dk}}</el-tag>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 添加或修改财务账单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="账单名称" prop="billName">
              <el-input v-model="form.billName" placeholder="请输入账单名称" />
            </el-form-item>
            <el-form-item label="买家" prop="buyers">
              <el-select v-model="form.buyers" filterable remote
                         placeholder="请选择买家" :remote-method="getClientOptions">
                <el-option v-for="buyer in clientOptions"
                           :key="buyer.clientId"
                           :value="buyer.clientName"
                           :label="buyer.clientName" />
              </el-select>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入电话" />
            </el-form-item>
            <el-form-item label="收款账户" prop="payee">
              <el-select v-model="form.payee" placeholder="请选择收款账户">
                <el-option v-for="pay in payeeOption" :label="pay.dictLabel" :value="pay.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="成本价" prop="costPrice">
              <el-input-number v-model="form.costPrice" :min="0" placeholder="请输入成本价" />
            </el-form-item>
            <el-form-item label="销售价" prop="sellPrice">
              <el-input-number v-model="form.sellPrice" :min="0" placeholder="请输入销售价" />
            </el-form-item>
            <el-form-item label="销售人" prop="sellBy">
              <el-select v-model="form.sellBy" filterable placeholder="请选择销售人">
                <el-option v-for="user in userList"
                           :key="user.userId"
                           :value="user.nickName"
                           :label="user.nickName" />
              </el-select>
            </el-form-item>
            <el-form-item label="配送费" prop="givePrice">
              <el-input-number v-model="form.givePrice" :min="0" />
            </el-form-item>
            <el-form-item label="配件成本" prop="partsPrice">
              <el-input-number v-model="form.partsPrice" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="支付方式" prop="paymentType">
          <el-select v-model="form.paymentType" placeholder="请选择支付方式">
            <el-option v-for="payment in paymentTypeOptions" :label="payment.label" :value="payment.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="支付详情" v-show="form.paymentType === 4">
          <div v-for="(json, key) in paymentJson" style="display: flex;flex-direction: row;margin-bottom: 5px">
            <el-select v-model="json.type" placeholder="请选择支付方式">
              <el-option v-for="payment in paymentTypeOptions" v-if="payment.value !== 4" :label="payment.label" :value="payment.value" />
            </el-select>
            <div style="width: 3px"></div>
            <el-input type="number" v-model="json.price" placeholder="请输入支付金额" @change="setSellPriceChange" style="width: 150px" />
            <div style="width: 3px"></div>
            <el-select v-model="json.payee" placeholder="请选择收款账户" clearable>
              <el-option v-for="pay in payeeOption" :label="pay.dictLabel" :value="pay.dictValue" />
            </el-select>
            <div style="margin-left: 3px">
              <el-button icon="el-icon-minus" plain circle size="mini" type="danger"
                         @click="delPaymentJson(key)" v-if="key > 1"></el-button>
            </div>
          </div>
          <!-- 支付详情 添加-->
          <el-button icon="el-icon-plus" plain circle size="mini"
                     type="primary" v-if="paymentJson.length < 4" @click="addPaymentJson"></el-button>
        </el-form-item>

        <el-form-item label="银行单号" v-show="form.paymentType === 6">
          <el-input v-model="paymentBankJson.number" placeholder="请输入银行交易单号" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBill, getBill, delBill, addBill, updateBill, exportBill, outGoodsBill, dataBill, conditionSearch, updateStatus } from "@/api/recovery/bill";
import {listBasicClient} from "@/api/basic/basicClient"
import {getGoods} from "@/api/recovery/goods";
import {getCollect} from "@/api/store/collect"
import {listUser} from "@/api/system/user"
import {listStock} from "@/api/recovery/stock"
import {strTranArray} from "@/utils/tran/shareUtils";
import {listTestValues} from "@/api/basic/testValues"
import $const from "@/utils/websocket/ServerPath";


export default {
  name: "Bill",
  components: {
  },
  data() {
    return {
      /*筛选条件*/
      conditionParams: {
        timeType: 'day',
        hasPayee: 'no'
      },
      /* 筛选结果*/
      conditionData: [],
      /*窗口开关*/
      conditionOpen: false,
      /* 支付详情 多种支付*/
      paymentJson: [
        {type: 1, payee: null, price: 0},
        {type: 2, payee: null, price: 0}
      ],
      /* 银行卡单号*/
      paymentBankJson: {
        type: 6,
        number: null
      },
      /*报价师列表*/
      offerNameOptions: [],
      /*支付方式列表*/
      paymentTypeOptions: $const.PAYMENT_OPTIONS,
      /*收款账户数据字典*/
      payeeOption: [],
      /* 统计数据和开关*/
      dataPrice: {costPrice: 0, sellPrice: 0, profitPrice: 0},
      dataOpen: false,
      //修改时间搜索范围
      updateTimeRange: [],
      //时间搜索范围
      createTimeRange: [],
      //退货商品信息
      outGoodsForm: {},
      //退货开关
      outGoodsOpen: false,
      //验机选项列表
      testValuesList: [],
      //仓库列表
      stockList: [],
      //用户列表
      userList: [],
      //详情信息
      detailInfo: null,
      //详情开关
      detailOpen: false,
      //客户列表
      clientOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 财务账单表格数据
      billList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsId: null,
        billName: null,
        goodsSn: null,
        costPrice: null,
        sellPrice: null,
        buyers: null,
        paymentType: null,
        status: null,
        type: null,
        sellBy: null,
        payee: null,
        offerName: null,
        params: {}
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        billName: [
          { required: true, message: "账单名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getDicts("dayu_offer_teach").then(response => {
      this.offerNameOptions = response.data;
    });
    this.getDicts("recovery_bill_payee").then(response => {
      this.payeeOption = response.data;
    });
    this.getList();
    listUser({}).then(resp => {
      this.userList = resp.rows;
    })
    listStock({}).then(resp => {
      this.stockList = resp.rows;
    })
    listTestValues({}).then(resp => {
      this.testValuesList = resp.rows;
    })

    this.getDicts("recovery_bill_give_type").then(res => {
      this.giveTypeOptions = res.data;
    })
  },
  methods: {
    bankNumber(row) {
      if(row.paymentDetail == null){
        return "";
      }
      let obj = JSON.parse(row.paymentDetail);
      if(obj.number == null) {
        return  "";
      }
      return obj.number;
    },
    giveFormat(row) {
      return this.selectDictLabel(this.giveTypeOptions, row.giveType);
    },
    handleStatus() {
      const ids = this.ids;
      for(let i = 0; i < ids.length; i++) {
        for(let j = 0; j < this.billList.length; j++) {
          if(ids[i] === this.billList[j].billId) {
            if(this.billList[j].status !== 1) {
              this.msgError("数据必须为待审核状态！")
              return
            }
          }
        }
      }
      this.$confirm("确认审核编号为 " + ids + " 的数据吗？", '警告', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        return updateStatus(ids);
      }).then(res => {
        this.getList();
        this.msgSuccess("操作成功!")
      })
    },
    /** 设置行背景颜色 */
    setRowClassName(data) {
      if(data.row.sellPrice < data.row.costPrice) {
        return "bg_red";
      }
      return "";
    },
    /** 前往打印页面*/
    gotoPrinting(row) {
      const billIds = row.billId || this.ids;
      let data = {ids: billIds};
      let buyers = ""; //同一个买家
      let sellBy = ""; //同一个销售人
      let type = null; //同一个账单类型
      for(let i = 0; i < billIds.length; i++) {
        for(let j = 0; j < this.billList.length; j++) {
          if(Number(billIds[i]) === this.billList[j].billId) {
            if(i === 0) {
              buyers = this.billList[j].buyers;
              sellBy = this.billList[j].sellBy;
              type = this.billList[j].type;
              break;
            }
            if(type !== this.billList[j].type) {
              this.msgError("请选择相同账单类型！");
              return
            }
            if(buyers !== this.billList[j].buyers) {
              this.msgError("请选择同一个买家！");
              return
            }
            if(sellBy !== this.billList[j].sellBy) {
              this.msgError("请选择同一个销售人！")
              return
            }
          }
        }
      }
      console.log("data: ", data)
      const url = this.$router.resolve({path: '/bill/printing', query : data})
      window.open(url.href, '_blank')
    },
    conditionChange(e) {
      conditionSearch(this.conditionParams).then(resp => {
        this.conditionData = resp.data;
      })
    },
    /*支付统计窗口*/
    handleCondition() {
      conditionSearch(this.conditionParams).then(resp => {
        this.conditionData = resp.data;
        this.conditionOpen = true;
      })
    },
    setSellPriceChange(e) {
      let price = 0;
      for(let i = 0; i < this.paymentJson.length; i++) {
        if(this.paymentJson[i].price != null) {
          price += Number(this.paymentJson[i].price);
        }
      }
      this.form.sellPrice = price;
    },
    /* 添加一行 支付详情*/
    addPaymentJson() {
      this.paymentJson.push({type: 1, payee: null, price: 0});
    },
    /*删除 一行支付详情*/
    delPaymentJson(key) {
      this.$delete(this.paymentJson, key);
    },
    // 报价师字典翻译
    offerNameFormat(row, column) {
      return this.selectDictLabel(this.offerNameOptions, row.offerName);
    },
    // 收款人字典翻译
    payeeFormatter(row, column) {
      return this.selectDictLabel(this.payeeOption, row.payee);
    },
    closeData() {
      this.dataOpen = false
    },
    openData() {
      this.dataOpen = true;
      this.dataPrice = {costPrice: 0, sellPrice: 0, profitPrice: 0};
      dataBill(this.queryParams).then(resp => {
        if(resp.data != null) {
          this.dataPrice = resp.data;
        }
      })
    },
    /** 修改时间*/
    updateTimeChange(e) {
      if(e == null) {
        this.$delete(this.queryParams.params, 'updateStartTime');
        this.$delete(this.queryParams.params, 'updateEndTime');
        return
      }
      this.$set(this.queryParams.params, 'updateStartTime', e[0]);
      this.$set(this.queryParams.params, 'updateEndTime', e[1]);
    },
    /** 创建时间选项*/
    createTimeChange(e) {
      if(e == null) {
        this.$delete(this.queryParams.params, 'createStartTime');
        this.$delete(this.queryParams.params, 'createEndTime');
        return
      }
      this.$set(this.queryParams.params, 'createStartTime', e[0]);
      this.$set(this.queryParams.params, 'createEndTime', e[1]);
    },
    /** 退货提交 */
    outSubmitForm() {
        outGoodsBill(this.outGoodsForm).then(resp => {
          this.msgSuccess("操作成功！")
          this.getList();
        })
      this.outGoodsOpen = false;
    },
    /** 退货关闭 */
    outCancel() {
      this.outGoodsOpen = false;
    },
    /** 验机报告 */
    testValuesFormatter(testValues) {
      testValues = testValues == null ? "" : testValues;
      let arr = strTranArray(testValues);
      let res = "";
      for(let i = 0; i < arr.length; i++) {
        for(let j = 0; j < this.testValuesList.length; j++) {
          if(arr[i] === this.testValuesList[j].valuesId) {
            res += "[" + this.testValuesList[j].valuesName + "]-";
            break;
          }
        }
      }
      return res.substring(0, res.length - 1);
    },
    /** 仓库格式 */
    stockFormatter(stockId) {
      for(let i = 0; i < this.stockList.length; i++) {
        if(stockId === this.stockList[i].stockId) {
          return this.stockList[i].stockName;
        }
      }
    },
    /** 用户格式 */
    userFormatter(userId) {
      for(let i = 0; i < this.userList.length; i++) {
        if(userId === this.userList[i].userId) {
          return this.userList[i].nickName;
        }
      }
    },
    /** 退库框 */
    handleReturnGoods(row) {
      this.outGoodsForm = {
        goodsId: row.goodsId,
        billId: row.billId,
        billName: row.billName,
        costPrice: 0,
        sellPrice: row.sellPrice,
        remark: null
      }
      this.outGoodsOpen = true;
    },
    /** 状态改变 */
    handleUpdateByStatus(row, status) {
      let str = "";
      switch (status) {
        case 2: str = "确定审核这条财务账单吗？";break;
        case 4: str = "确定作废这个财务账单吗？";break;
      }
      let bill = {
        billId : row.billId,
        status : status
      }
      this.$confirm(str, "警告", {
        confirmButtonText: '确定',
        cancelButtonText: '关闭',
        type: "warning"
      }).then(function () {
        return updateBill(bill);
      }).then(resp => {
        this.getList();
        this.msgSuccess("操作成功！")
      })
    },
    /** 打开详情框 */
    async handleDetail(row) {
      this.detailInfo = {
        goodsInfo: null,
        collectInfo: null,
        row: row
      }
      if(row.goodsId != null) {
        await getGoods(row.goodsId).then(resp => {
          this.detailInfo.goodsInfo = resp.data
        })
        if(this.detailInfo.goodsInfo.storeId != null) {
          await getCollect(this.detailInfo.goodsInfo.storeId).then(resp => {
            this.detailInfo.collectInfo = resp.data;
          })
        }

      }
      this.detailOpen = true;
    },
    /** 获取客户列表 */
    getClientOptions(e) {
      return listBasicClient({clientName: e}).then(resp => {
        let params = {clientName: e};
        listBasicClient(params).then(resp => {
          this.clientOptions = resp.rows;
        })
      })
    },
    /** 账单类型 */
    typeFormatter(row) {
      switch (row.type) {
        case 1: return "商品出售";
        case 2: return "自定义账单";
        case 3: return "退货账单";
      }
    },
    /** 查询财务账单列表 */
    getList() {
      this.loading = true;
      listBill(this.queryParams).then(response => {
        this.billList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        billId: null,
        goodsId: null,
        billName: null,
        goodsSn: null,
        costPrice: null,
        sellPrice: null,
        profit: null,
        buyers: '零售',
        paymentType: 1,
        status: 0,
        type: null,
        createId: null,
        createBy: null,
        createTime: null,
        updateId: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        sellBy: null,
        payee: null,
        paymentDetail: null,
        mobile: null
      };
      this.resetForm("form");
      this.paymentJson = [
        {type: 1, payee: null, price: 0},
        {type: 2, payee: null, price: 0}
      ];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.closeData();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.createTimeRange = [];
      this.createTimeChange(null);
      this.updateTimeRange = [];
      this.updateTimeChange(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.billId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加财务账单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const billId = row.billId || this.ids
      getBill(billId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改财务账单";
        if(this.form.paymentDetail != null) {
          if(this.form.paymentType === 4) {
            this.paymentJson = JSON.parse(this.form.paymentDetail);
          }else {
            this.paymentBankJson = JSON.parse(this.form.paymentDetail);
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.paymentType === 4) {
            this.form.paymentDetail = JSON.stringify(this.paymentJson);
          }
          if(this.form.paymentType === 6) {
            this.form.paymentDetail = JSON.stringify(this.paymentBankJson);
          }
          if(this.form.mobile != null) {
            this.form.buyers += " " + this.form.mobile;
          }
          if (this.form.billId != null) {
            updateBill(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.type = 2;
            this.form.status = 1;
            addBill(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const billIds = row.billId || this.ids;
      this.$confirm('是否确认删除财务账单编号为"' + billIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBill(billIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      let nt = null;
      this.$confirm('是否确认导出所有财务账单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
           nt = this.$notify({
            title: '导出提醒',
            message: '服务器正在生成数据文件，请稍等！',
            duration: 0
          })
          return exportBill(queryParams);
        }).then(response => {
          nt.close();
          this.download(response.msg);
        })
    }
  }
};
</script>

<style>
  .el-table .bg_red {
    color: red;
  }
  .table-row {
    white-space: nowrap;
    overflow: hidden;
  }
</style>
